<!-- 新增/修改弹框 -->
<template>
  <div>
    <XFDialog v-model="dialogVisible" @submit="submit" @closed="close">
      <template #default>
        <el-form ref="formRef"
                 label-width="auto"
                 :model="state.form"
                 :rules="state.rules">
          <el-form-item label="名称" prop="kname">
            <el-input v-model="state.form.kname"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="state.form.description"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </XFDialog>
  </div>
</template>

<script setup>
import XFDialog from "@/views/component/XFDialog.vue";
import {reactive, defineProps, computed, ref} from "vue";
import api from "@/utils/api.js";
import {ElMessage} from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(["update:modelValue", "updateTable"])

const formRef = ref(null);
// 使用计算属性替代 watch
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emits("update:modelValue", value)
  }
})

const state = reactive({
  visible: false,
  title: "新增",
  width: "500px",
  form: {},
  rules: {
    kname: [
      {required: true, message: "请输入名称", trigger: "blur"}
    ],
  }
})

const submit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      api.knowledgeInfo.insert(state.form).then((res) => {
        if (res?.code === 200) {
          ElMessage({
            message: "新增成功",
            type: "success"
          })
          dialogVisible.value = false;
          emits("updateTable")
        } else {
          ElMessage({
            message: res?.msg || "新增失败",
            type: "error"
          })
        }
      })
    }
  })
}

/**
 * 关闭逻辑
 */
const close = () => {
  state.form = {}
}
</script>
<style scoped>

</style>